<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace app\wechat\service;

use app\admin\common\AdminException;

final class Menu
{
    /**
     * 获取自定义菜单类型列表。
     *
     * @return string[]
     */
    public function get_menu_type_list()
    {
        return array(
            'view' => '跳转URL',
            'click' => '点击推事件',
            'scancode_push' => '扫码推事件',
            'scancode_waitmsg' => '扫码推事件且弹出“消息接收中”提示框',
            'pic_sysphoto' => '弹出系统拍照发图',
            'pic_photo_or_album' => '弹出拍照或者相册发图',
            'pic_weixin' => '弹出微信相册发图器',
            'location_select' => '弹出地理位置选择器',
            'media_id' => '下发消息（除文本消息）',
            'view_limited' => '跳转图文消息URL',
            'miniprogram' => '小程序',
        );
    }

    /**
     * 上传菜单信息到微信服务器。
     *
     * @return void
     */
    public function upload_menu_to_wx($mp_id)
    {
        $button_array = $this->_create_button_array($mp_id);

        $wxobj = service('wechat/mp')->get_wx_object($mp_id);
        $result = $wxobj->createMenu(array('button' => $button_array));
        if ($result === false) {
            throw new AdminException('[' . $wxobj->getErrCode() . '] ' . $wxobj->getErrText());
        }
    }

    private function _create_button_array($mp_id)
    {
        $button_array = array();

        $menu_tree = model('wechat/menu')->get_menu_tree($mp_id);

        foreach ($menu_tree as $menu_info) {
            $button_array[] = $this->_create_button_item($menu_info);
        }

        return $button_array;
    }

    private function _create_button_item($menu_info)
    {
        $menu_info['content'] = helper('admin/json')->decode($menu_info['content']);

        $button_item = array();
        $button_item['name'] = $menu_info['title'];

        if ($menu_info['type']) {
            $content = isset($menu_info['content'][$menu_info['type']]) ? $menu_info['content'][$menu_info['type']] : array();
            if ($content) {
                $button_item = array_merge($button_item, $content);
                $button_item['type'] = $menu_info['type'];
            }
        } else if (isset($menu_info['_child'])) {
            $button_item['sub_button'] = array();
            foreach ($menu_info['_child'] as $child_menu) {
                $button_item['sub_button'][] = $this->_create_button_item($child_menu);
            }
        }

        return $button_item;

    }


//     /**
//      * 获取微信 SDK 调起主动对象
//      * @author geeson myrhzq@qq.com
//      * @param $options array
//      */
//     function getWechatActiveObj($mid = '')
//     {
//         if ($mid == '') {
//             if (empty(session('mp_options'))) {
//                 exit('公众号标识mid不存在');
//             }
//         }
//         if ($mid) {
//             $mpInfo = getMpInfo($mid);
//             $options = array(
//                 'appid' => $mpInfo['appid'],
//                 'appsecret' => $mpInfo['appsecret'],
//                 'token' => $mpInfo['valid_token'],
//                 'encodingaeskey' => $mpInfo['encodingaeskey']
//             );
//         }
//         include_once EXTEND_PATH . "wechatSdk/wechat.class.php";
//         empty($options) ? $options = session('mp_options') : $options = $options;
//         $weObj = new \Wechat($options);
//         return $weObj;
//     }



//     public function createMenu($data){
//         if (!$this->access_token && !$this->checkAuth()) return false;
//         $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
//         if ($result)
//         {
//             $json = json_decode($result,true);
//             if (!$json || !empty($json['errcode'])) {
//                 $this->errCode = $json['errcode'];
//                 $this->errMsg = $json['errmsg'];
//                 return false;
//             }
//             return true;
//         }
//         return false;
//     }



//     foreach ($result as &$row) {
//         empty($row['content']) && $row['content'] = uniqid();
//         switch ($row['type']) {
//             case 'miniprogram':
//                 list($row['appid'], $row['url'], $row['pagepath']) = explode(',', $row['content'] . ',,');
//                 break;
//             case 'view':
//                 $row['url'] = preg_match('#^(\w+:)?//#i', $row['content']) ? $row['content'] : url($row['content'], '', true, true);
//                 break;
//             case 'event':
//                 if (isset($menu_type[$row['content']])) {
//                     $row['type'] = $row['content'];
//                     $row['key'] = "wechat_menu#id#{$row['id']}";
//                 }
//                 break;
//             case 'media_id':
//                 $row['media_id'] = $row['content'];
//                 break;
//             default :
//                 (!in_array($row['type'], $menu_type)) && $row['type'] = 'click';
//                 $row['key'] = "{$row['content']}";
//         }
//         unset($row['content']);
//     }
//     $menus = GetRreeByMpMenu($result, 'index', 'pindex', 'sub_button');
//     foreach ($menus as &$menu) {
//         unset($menu['index'], $menu['pindex'], $menu['id']);
//         if (empty($menu['sub_button'])) {
//             continue;
//         }
//         foreach ($menu['sub_button'] as &$submenu) {
//             unset($submenu['index'], $submenu['pindex'], $submenu['id']);
//         }
//         unset($menu['type']);
//     }
//     $result = createMpMenu(['button' => $menus]);
//     if (isset($result->errCode)) {
//         ajaxMsg(0, 'errCode: ' . $result->errCode . ' errMsg: ' . $result->errMsg);
//     } elseif ($result == true) {
//         ajaxMsg(1, '发布成功');
//     }
}
